package com.elitetyc.eliteim.server.handler.impl;

import com.elitetyc.eliteim.common.constant.Constants;
import com.elitetyc.eliteim.common.handler.impl.BaseMsgHandler;
import com.elitetyc.eliteim.common.model.impl.U2UMsg;
import com.elitetyc.eliteim.common.proto.RequestProto;
import com.elitetyc.eliteim.server.holder.SessionSocketHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 用户到用户消息处理
 * @Date 2021/9/18 9:39
 */
@Component
@Slf4j
public class U2UMsgHandlerImpl extends BaseMsgHandler<U2UMsg> {

    @Override
    public boolean support(int type) {
        return type == Constants.RequestType.U2U;
    }

    @Override
    public void handleMsg(ChannelHandlerContext ctx, RequestProto.RequestProtocol source, U2UMsg msg) {
        final SessionSocketHolder.ServerChannelUserInfo senderUserInfo =
                SessionSocketHolder.CHANNEL_USER_INFO_MAP.get(msg.sender.getUserId());
        final SessionSocketHolder.ServerChannelUserInfo receiveUserInfo =
                SessionSocketHolder.CHANNEL_USER_INFO_MAP.get(msg.receiveId);
        if (receiveUserInfo!=null){
            NioSocketChannel channel = receiveUserInfo.getChannel();
            channel.writeAndFlush(source).addListener(future -> {
                String logStr = buildLogInfo(senderUserInfo,receiveUserInfo,msg);
                if (future.isSuccess()){
                    log.info("success:"+logStr);
                }else {
                    log.error("error:"+logStr);
                }
            });
        }else {
            log.warn("用户{}不在线",msg.receiveId);
            // 用户不在线,消息放到队列 TODO

        }

    }

    private String buildLogInfo(SessionSocketHolder.ServerChannelUserInfo sender,
                                SessionSocketHolder.ServerChannelUserInfo receiver,
                                U2UMsg msg){
        return String.format("用户【%s(%s)】向用户【%s(%s)】发送消息【%s】",
                sender.getUserInfo().getUserId(),sender.getUserInfo().getUserName(),
                receiver.getUserInfo().getUserId(),receiver.getUserInfo().getUserName(),
                msg.content);
    }
}
